<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="departmentList" default-expand-all :expand-on-click-node="false" :props="{label:'name'}">
        <template #default="{data}"> <!-- data返回的数据是当前数组的对象数据,相当于data是数据遍历的每一项 -->
          <el-row justify="space-between" style="width:100%;" type="flex">
            <!-- 部门名字 -->
            <el-col>
              <span>{{ data.name }}</span>
            </el-col>
            <!-- 右侧操作 -->
            <el-col style="width:230px;">
              <!-- 做做人的名子，不会渲染 -->
              <span style="margin:0 20px">{{ data.managerName }}</span>
              <!-- 下拉菜单 -->
              <el-dropdown @command="handleCommand($event,data.id)"> <!-- 下拉菜单自定义事件，$event可接收子传父数据，类如类型、id -->
                <span class="el-dropdown-link">
                  下拉菜单<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDep ref="depRef" :visible.sync="visible" :pid="pid" @onSuccess="onload" />
  </div>
</template>
<script>
import { delDepAPI, getDepartmentListAPI } from '@/api/department'
import { convertToTree } from '@/utils'
import AddDep from '@/views/department/component/add-dep.vue'
export default {
  name: 'Department',
  components: { AddDep },
  data() {
    return {
      // 默认模块名是label，切换要在：props={babel:name}
      departmentList: [],
      visible: false,
      pid: null
    }
  },
  created() {
    this.onload()
  },
  methods: {
    // 1.需要进行型删改查，封装方法多次调用
    async onload() {
      const res = await getDepartmentListAPI()
      const tree = convertToTree(res.data)
      this.departmentList = tree
    },
    // 2.点击下拉菜单，利用下拉菜单的自定义事件进行增删改查
    async handleCommand(type, id) {
      if (type === 'add') {
        this.visible = true
        this.pid = id
        return
      }
      // 3.编辑按钮调用子组件方法获取部门详情
      if (type === 'edit') {
        this.visible = true
        // 当点击编辑按钮，提前把id赋值给formData
        this.$refs.depRef.formData.id = id
        this.$refs.depRef.getDpmDetail(id)
        return
      }
      // 删除功能
      await this.$confirm('确定删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delDepAPI(id)
      this.$message.success('删除成功')
      this.onload()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
